package com.clas.liu.myapplication.view.adapter;

import android.content.Context;
import android.support.annotation.NonNull;
import android.support.v4.view.PagerAdapter;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;

import com.clas.liu.myapplication.R;
import com.clas.liu.myapplication.model.entity.banner.BannerData;
import com.squareup.picasso.Picasso;

import java.util.List;

/**
 * Created by liu on 2019/2/28.
 */

public class BannerViewPagerAdapter extends PagerAdapter {

    public static final int COUNT = Integer.MAX_VALUE;
    private List<BannerData> mBanners;
    private Context context;

    public BannerViewPagerAdapter(Context context, List<BannerData> mBanners) {
        this.context = context;
        this.mBanners = mBanners;
    }

    @Override
    public int getCount() {
        return COUNT;
    }

    @Override
    public boolean isViewFromObject(@NonNull View view, @NonNull Object object) {
        return view == object;
    }

    @NonNull
    @Override
    public Object instantiateItem(@NonNull ViewGroup container, int position) {
        ImageView image = new ImageView(container.getContext());
        image.setScaleType(ImageView.ScaleType.FIT_XY);
        image.setTag(position);
        if (mBanners != null)
            Picasso.with(context).load(mBanners.get(position % mBanners.size()).getUrl()).
                    placeholder(R.mipmap.ic_news_listview_img_loading)
                    .error(R.mipmap.ic_news_listview_img_loading).into(image);
        else Picasso.with(context).load(R.mipmap.ic_news_listview_img_loading).
                placeholder(R.mipmap.ic_news_listview_img_loading)
                .error(R.mipmap.ic_news_listview_img_loading).into(image);
        container.addView(image);
        return image;
    }

    @Override
    public void destroyItem(@NonNull ViewGroup container, int position, @NonNull Object object) {
        container.removeView(container.findViewWithTag(position));
    }

    public void updateBanners(List<BannerData> mBanners) {
        this.mBanners = mBanners;
        this.notifyDataSetChanged();
    }
}
